package hn.info.hockeynews.fragments;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import hn.info.hockeynews.R;
import hn.info.hockeynews.activities.LivetickerActivity;
import hn.info.hockeynews.activities.MainActivity;
import hn.info.hockeynews.dao.DaoMaster;
import hn.info.hockeynews.dao.DaoSession;
import hn.info.hockeynews.dao.Entry;
import hn.info.hockeynews.dao.Match;
import hn.info.hockeynews.dao.MatchDao;
import hn.info.hockeynews.dao.DaoMaster.DevOpenHelper;
import hn.info.hockeynews.dao.MatchDao.Properties;
import hn.info.hockeynews.helpers.ConnectionChecker;
import hn.info.hockeynews.helpers.DBHelperMatches;
import hn.info.hockeynews.helpers.JSONAsync;
import hn.info.hockeynews.service.DatabaseService;
import hn.info.hockeynews.service.GeoLoggerService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import hn.info.hockeynews.dao.DaoMaster.DevOpenHelper;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class Fragment0 extends ListFragment {

	private TextView ve;
	private Button bt;
	private View v;
	private TextView t;
	private ConnectionChecker cc;
	private JSONAsync as;
	private ListView lv;
	private ArrayList<String> oblist = new ArrayList<String>();
    private List<Match> matches;
	private Long listId;
	private DBHelperMatches dbh;
	private DatabaseService dbs;
	private DevOpenHelper helper;
	
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, oblist));	
		dbh = new DBHelperMatches();
		
		/**
		 * check if you already fetched data from json, if not get data from db
		 * */
		if(dbh.checkData().equals("null"))
		{
			fetchJSON();
		}
		
		if(dbh.checkData().equals("notnull"))
		{

			helper = new DaoMaster.DevOpenHelper(getActivity(), "matches-db", null);
			dbh.killDB(helper);
			fetchJSON();
		}
 
    }

    /**
     * open a single match to see ticker entries
     * */
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	
    	stopGeoLoggerService();
    	matches = dbh.getMatchData();
    	for(int i = 0; i < matches.size(); i++)
    	{
	    	if(id == i)
	    	{	 
	    		 listId = matches.get(i).getMatch_id();
	    		 String awayTeam = matches.get(i).getAway_name();
	    		 String homeTeam = matches.get(i).getHome_name();
	    		 
	    		 Log.i("FragmentList", "Item clicked: " + this.listId);
	              
	    	    
	    	        Intent intent = new Intent();
	    	        intent=new Intent(getActivity(), LivetickerActivity.class);
	    	        //Passing vars to the Activity before it starts
	    	        Bundle b = new Bundle();
	    	        b.putLong("match_id", listId);
	    	        b.putString("hometeam", homeTeam);
	    	        b.putString("awayteam", awayTeam);
	    	        
	    	        intent.putExtras(b);
	    	        startActivity(intent);
	    	}
       
    	}

    	
    }
    
    /**
     * fetch all the matches from the database
     * */
    public void fetchJSON()
    {
    	
		try {
	        as = new JSONAsync();
			as.settId("164");
			as.setUrl("http://hockey-news.info/androidapp/index.php");
			as.setTag("getMatches");
			JSONObject obj = as.getData();
			JSONArray menuitemArray = obj.getJSONArray("matches");
			
				for (int i = 0; i < menuitemArray.length(); i++) 
				{
					
					JSONObject mob = menuitemArray.getJSONObject(i);
					JSONObject l1 = mob.getJSONObject("match");
					
					//"match":{"match_id":"164","home":"http:\/\/at.hockey-news.info\/images\/LogosLiveticker\/99ers.png",
					//"home_name":"99ers","away":"http:\/\/at.hockey-news.info\/images\/LogosLiveticker\/hci.png",
					//"away_name":"Innsbruck","matchdate":"2012-12-02 17:30:00","info":"","running":"0","overtime_length":"5",
					//"head1":"DREMELJ\tIgor","head2":"KAMSEK\tLuka","linesman1":"JOHNSTONE\tMichael",
					//"linesman2":"TRATTNIG\tRoman","spectators":"0","roundid":"27","active":"1"}
					Timestamp tstamp = new Timestamp(System.currentTimeMillis()); 
					Match m = new Match(Long.valueOf(l1.getString("match_id")), l1.getString("home"), l1.getString("home_name"), 
							l1.getString("away"), l1.getString("away_name"), l1.getString("matchdate"), 
							l1.getString("info"), Integer.valueOf(l1.getString("running")), Integer.valueOf(l1.getString("overtime_length")), l1.getString("head1"),
							l1.getString("head2"), l1.getString("linesman1"), l1.getString("linesman2"), Integer.valueOf(l1.getString("spectators")),
							Integer.valueOf(l1.getString("roundid")), Integer.valueOf(l1.getString("active")), tstamp);
			
					
					helper = new DaoMaster.DevOpenHelper(getActivity(), "matches-db", null);
					
					dbh.insertMatch(m, helper);
				}
				
			
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(matches == null)
			{
				matches =  dbh.getMatchData();
				for(Match m1 : matches)
				{
					oblist.add(m1.getAway_name() + " - " + m1.getHome_name() + "\nDatum:"+m1.getMatchdate());	
				}
			}
			
		}
    
    
	
    public void startDatabaseService()
    {
		Context ctx = (Context)Fragment0.this.getActivity();
        ctx.startService(new Intent(getActivity(), GeoLoggerService.class));
    }
	
	public void stopGeoLoggerService() {
		Context ctx = (Context)Fragment0.this.getActivity();
        ctx.stopService(new Intent(getActivity(), GeoLoggerService.class));
	}
}
